package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_DATA_SOURCE_TYPE;
import com.netsdk.lib.enumeration.ENUMERROR;
import com.netsdk.lib.structure.NET_COMPLIANT_INFO;
import com.netsdk.lib.structure.NET_VEHICLEDETECT_RULE_INFO;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import static com.netsdk.lib.NetSDKLib.EM_ANALYSE_EVENT_TYPE.EM_ANALYSE_EVENT_TRAFFICJUNCTION;
import static com.netsdk.lib.Utils.getOsPrefix;
import static com.netsdk.lib.enumeration.EM_EVENT_IVS_TYPE.EVENT_IVS_VEHICLEDETECT;

/**
 * @author 291189
 * @version 1.0
 * @description ERR230519045
 * @date 2023/5/29 10:36
 */
public class VehicleDetectRuleInfoDemo {

    // SDk对象初始化
    public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

    // 判断是否初始化
    private static boolean bInit = false;
    // 判断log是否打开
    private static boolean bLogOpen = false;
    // 设备信息
    private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
    // 登录句柄
    private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);


    // 回调函数需要是静态的，防止被系统回收
    // 断线回调
    private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
    // 重连回调
    private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

    // 编码格式
    public static String encode;

    static {
        String osPrefix = getOsPrefix();
        if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
            encode = "GBK";
        } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
            encode = "UTF-8";
        }
    }

    /**
     * 获取当前时间
     */
    public static String GetDate() {
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
    }

    /**
     * 初始化SDK库
     */
    public static boolean Init() {
        bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
        if (!bInit) {
            System.out.println("Initialize SDK failed");
            return false;
        }
        // 配置日志
        VehicleDetectRuleInfoDemo.enableLog();

        // 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
        netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

        // 设置登录超时时间和尝试次数，可选
        // 登录请求响应超时时间设置为3S
        int waitTime = 3000;
        // 登录时尝试建立链接 1 次
        int tryTimes = 1;
        netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
        // 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
        // 接口设置的登录设备超时时间和尝试次数意义相同,可选
        NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
        // 登录时尝试建立链接的超时时间
        netParam.nConnectTime = 10000;
        // 设置子连接的超时时间
        netParam.nGetConnInfoTime = 3000;
        netsdk.CLIENT_SetNetworkParam(netParam);
        return true;
    }

    /**
     * 打开 sdk log
     */
    private static void enableLog() {
        NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
        File path = new File("sdklog/");
        if (!path.exists())
            path.mkdir();

        // 这里的log保存地址依据实际情况自己调整
        String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
        setLog.nPrintStrategy = 0;
        setLog.bSetFilePath = 1;
        System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
        System.out.println(logPath);
        setLog.bSetPrintStrategy = 1;
        bLogOpen = netsdk.CLIENT_LogOpen(setLog);
        if (!bLogOpen)
            System.err.println("Failed to open NetSDK log");
    }

    /**
     * 高安全登录
     */
    public void loginWithHighLevel() {
        // 输入结构体参数
        NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
            {
                szIP = m_strIpAddr.getBytes();
                nPort = m_nPort;
                szUserName = m_strUser.getBytes();
                szPassword = m_strPassword.getBytes();
            }
        };
        // 输出结构体参数
        NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

        // 写入sdk
        m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
                    netsdk.CLIENT_GetLastError());
        } else {
            deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
            System.out.println("Login Success");
            System.out.println("Device Address：" + m_strIpAddr);
            System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
        }
    }

    /**
     * 退出
     */
    public void logOut() {
        if (m_hLoginHandle.longValue() != 0) {
            netsdk.CLIENT_Logout(m_hLoginHandle);
            System.out.println("LogOut Success");
        }
    }

    /**
     * 清理sdk环境并退出
     */
    public static void cleanAndExit() {
        if (bLogOpen) {
            netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
        }
        netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
        System.exit(0);
    }


    /**
     * 添加智能分析任务测试
     */
    int myTaskID=0;
    public void AddAnalyseTaskLEFTDETECTION() {

        /**
         主动推送图片文件，添加任务时无规则和图片信息，通过推送图片接口，每张图片中带有不同的规则信息（目前能源场景中使用）, 对应 NET_PUSH_PICFILE_BYRULE_INFO
         */
        int emDataSourceType = EM_DATA_SOURCE_TYPE.EM_DATA_SOURCE_PUSH_PICFILE.getType();
        // 入参结构体
        NetSDKLib.NET_PUSH_PICFILE_INFO msg = new NetSDKLib.NET_PUSH_PICFILE_INFO();



        /**
         * EM_ANALYSE_TASK_START_RULE  {@link com.netsdk.lib.enumeration.EM_ANALYSE_TASK_START_RULE}
         */
        msg.emStartRule=0;


        NetSDKLib.NET_ANALYSE_RULE stuRuleInfo = msg.stuRuleInfo;

        stuRuleInfo.nRuleCount=1;

        NetSDKLib.NET_ANALYSE_RULE_INFO stuRuleInfo1 = stuRuleInfo.stuRuleInfos[0];
        stuRuleInfo1.dwRuleType=EVENT_IVS_VEHICLEDETECT.getType();

        NET_VEHICLEDETECT_RULE_INFO rule = new NET_VEHICLEDETECT_RULE_INFO();

        rule.nSnapThreshold=90;

        rule.nDetectRegionPoint=4;
        // 设置检测区域
        rule.stuDetectRegion[0].nX = 0;
        rule.stuDetectRegion[0].nY = 0;
        rule.stuDetectRegion[1].nX = 0;
        rule.stuDetectRegion[1].nY = 8191;
        rule.stuDetectRegion[2].nX = 8191;
        rule.stuDetectRegion[2].nY = 8191;
        rule.stuDetectRegion[3].nX = 8191;
        rule.stuDetectRegion[3].nY = 0;
        rule. bFeatureExtractEnable=1;
        NET_COMPLIANT_INFO stuCompliant
                = rule.stuCompliant;
        stuCompliant.nCompliantType=2;


        stuRuleInfo1.pReserved=new Memory(rule.dwSize );
        stuRuleInfo1.pReserved.clear(rule.dwSize);
        ToolKits.SetStructDataToPointer(rule, stuRuleInfo1.pReserved,0);


        msg.write();

        NetSDKLib.NET_OUT_ADD_ANALYSE_TASK pOutParam = new NetSDKLib.NET_OUT_ADD_ANALYSE_TASK();

        if (netsdk.CLIENT_AddAnalyseTask(m_hLoginHandle, emDataSourceType, msg.getPointer(), pOutParam, 5000)) {
            myTaskID = pOutParam.nTaskID;
            System.out.println("AddAnalyseTask Succeed! " + "任务ID:" + myTaskID + "任务对应的虚拟通道号" + pOutParam.nVirtualChannel);
        } else {
            System.err.printf("AddAnalyseTask Failed!Last Error[0x%x]\n", netsdk.CLIENT_GetLastError());

        }
        msg.read();
        Native.free(Pointer.nativeValue(stuRuleInfo1.pReserved)); //清理内存
        Pointer.nativeValue(stuRuleInfo1.pReserved, 0);
    }



    /**
     * 4-推送图片
     */
    public void pushAnalysePictureFile1(String str1, String fileId6) {
        System.out.println("startTime------------:" + System.currentTimeMillis());
        NetSDKLib.NET_IN_PUSH_ANALYSE_PICTURE_FILE analysePictureFile_in = new NetSDKLib.NET_IN_PUSH_ANALYSE_PICTURE_FILE();
        System.out.println(" taskId:" + myTaskID);
        analysePictureFile_in.nTaskID = myTaskID;
        analysePictureFile_in.nPicNum = 1;
        String str = str1;
        int totalLen = 0; // 这是总的图片缓冲区长度
        byte[] testFileBuffer1 = ToolKits.readPictureToByteArray(str);
        String fileId = fileId6;
        System.out.println("解析任务：fileId=" + fileId);

        byte[] fileId1 = fileId.getBytes();
        System.arraycopy(fileId1, 0, analysePictureFile_in.stuPushPicInfos[0].szFileID, 0, fileId1.length);
        System.out.println("testFileBuffer1:" + testFileBuffer1.length);
        if (testFileBuffer1 != null) {
            analysePictureFile_in.stuPushPicInfos[0].nLength = testFileBuffer1.length;
            // 偏移量，有多张图时这里要特别注意
            analysePictureFile_in.stuPushPicInfos[0].nOffset = totalLen;
            // 总的长度是各个图的累加
            totalLen = totalLen + analysePictureFile_in.stuPushPicInfos[0].nLength;
        }
        analysePictureFile_in.nBinBufLen = totalLen;
        // 分配内存
        analysePictureFile_in.pBinBuf = new Memory(totalLen);
        // 清理内存
        analysePictureFile_in.pBinBuf.clear(totalLen);

        if (testFileBuffer1 != null) {
            // 第一张图写入缓存
            analysePictureFile_in.pBinBuf.write(analysePictureFile_in.stuPushPicInfos[0].nOffset, testFileBuffer1, 0,
                    analysePictureFile_in.stuPushPicInfos[0].nLength);
        }

        NetSDKLib.NET_OUT_PUSH_ANALYSE_PICTURE_FILE analysePictureFile_out = new NetSDKLib.NET_OUT_PUSH_ANALYSE_PICTURE_FILE();

        boolean aBoolean1 = netsdk.CLIENT_PushAnalysePictureFile(m_hLoginHandle, analysePictureFile_in,
                analysePictureFile_out, 30000);
        if (!aBoolean1) {
            System.out.println("推送图片任务失败！");
            System.out.println("推图错误码：" + netsdk.CLIENT_GetLastError());
        } else {
            System.out.println("推图成功！！!");
        }

        Native.free(Pointer.nativeValue(analysePictureFile_in.pBinBuf)); //清理内存
        Pointer.nativeValue(analysePictureFile_in.pBinBuf, 0);
    }

    public void pushs() {
        for (int i = 0; i < 1; i++) {
            String str = "D:\\1.jpg";
            String fileId = (i + 1) + "";
            pushAnalysePictureFile1(str, fileId);

        }
    }
    NetSDKLib.LLong AttachHandle=null;
    /**
     * 2-订阅分析结果
     */
    public void attachAnalyseTaskResult() {
        NetSDKLib.NET_IN_ATTACH_ANALYSE_RESULT pInParam4 = new NetSDKLib.NET_IN_ATTACH_ANALYSE_RESULT();
        pInParam4.nTaskIDs[0] = myTaskID;
        pInParam4.nTaskIdNum = 1;
        NetSDKLib.NET_ANALYSE_RESULT_FILTER result_filter = new NetSDKLib.NET_ANALYSE_RESULT_FILTER();
        result_filter.nEventNum = 0;

     //   result_filter.dwAlarmTypes[0] = NetSDKLib.EVENT_IVS_VEHICLEDETECT;
        pInParam4.cbAnalyseTaskResult = CbfAnalyseTaskResultCallBack.getInstance();
        pInParam4.stuFilter = result_filter;
        AttachHandle = netsdk.CLIENT_AttachAnalyseTaskResult(m_hLoginHandle, pInParam4, 30000);
        if (AttachHandle.longValue() == 0) {
            System.err.println("订阅lLong1：" + AttachHandle);
            System.err.println("订阅错误码：" + netsdk.CLIENT_GetLastError());
        } else {
            System.out.println("订阅成功taskId={}:" + myTaskID);
        }
    }

    /**
     * 智能分析结果订阅函数原型
     */
    private static class CbfAnalyseTaskResultCallBack implements NetSDKLib.fAnalyseTaskResultCallBack {

        private final File picturePath;

        private CbfAnalyseTaskResultCallBack() {

            picturePath = new File("./AnalyzerPicture/result/");
            if (!picturePath.exists()) {
                picturePath.mkdirs();
            }
        }

        private static class CallBackHolder {
            private static CbfAnalyseTaskResultCallBack instance = new CbfAnalyseTaskResultCallBack();
        }

        public static CbfAnalyseTaskResultCallBack getInstance() {
            return CbfAnalyseTaskResultCallBack.CallBackHolder.instance;
        }

        @Override
        public int invoke(NetSDKLib.LLong lAttachHandle, Pointer pstAnalyseTaskResult, Pointer pBuf, int dwBufSize,
                          Pointer dwUser) {
            NetSDKLib.NET_CB_ANALYSE_TASK_RESULT_INFO task = new NetSDKLib.NET_CB_ANALYSE_TASK_RESULT_INFO();
            ToolKits.GetPointerData(pstAnalyseTaskResult, task);

            System.out.println("进入回调-----------------------------------");
        System.out.println("dwBufSize:"+dwBufSize);
            System.out.println("task.nTaskResultNum:" + task.nTaskResultNum);
            for (int i = 0; i < task.nTaskResultNum; i++) {


                int nRetEventInfoExNum
                        = task.stuTaskResultInfos[0].nRetEventInfoExNum;
                int nEventCount = task.stuTaskResultInfos[0].nEventCount;

                System.out.println("返回扩展事件信息个数:"+nRetEventInfoExNum);

                System.out.println("实际的事件个数:"+nEventCount);

                for (int j = 0; j < task.stuTaskResultInfos[0].nEventCount; j++) {
                    int emEventType = task.stuTaskResultInfos[i].stuEventInfos[i].emEventType;
                    switch (emEventType) {

                        case EM_ANALYSE_EVENT_TRAFFICJUNCTION: {

                            System.out.println("交通路口事件");
                            //路口事件，抓拍车牌

                            NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO trafficJunction=new NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO();
                            //获取车牌信息
                            ToolKits.GetPointerData(task.stuTaskResultInfos[i].stuEventInfos[j].pstEventInfo ,trafficJunction);

                            String date = trafficJunction.UTC.toStringTime();

                            NetSDKLib.DEV_EVENT_TRAFFIC_TRAFFICCAR_INFO trafficCar=trafficJunction.stTrafficCar;
                            try {
                                System.out.println(date+" traffic number:"+new String(trafficCar.szPlateNumber,
                                        encode)+",plate color:"+
                                        new String(trafficCar.szPlateColor,encode));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                          //  NetSDKLib.NET_MSG_OBJECT stuVehicle=     trafficJunction.stuObject;
                            NetSDKLib.NET_MSG_OBJECT stuVehicle = trafficJunction.stuVehicle;


                            byte[] szObjectType
                                    = stuVehicle.szObjectType;
                            try {
                                System.out.println("物体类型:"+new String(szObjectType,encode));
                                System.out.println("置信度(0~255),值越大表示置信度越高:"+stuVehicle.nConfidence);
                                System.out.println("表示车牌、车身等物体主要颜色；按字节表示,分别为红、绿、蓝和透明度:"+stuVehicle.rgbaMainColor);
                                System.out.println("物体上相关的带0结束符文本,比如车牌,集装箱号等等:"+new String(stuVehicle.szText,encode));
                                System.out.println("物体子类别:"+new String(stuVehicle.szObjectSubType,encode));
                                System.out.println("车辆子品牌:"+stuVehicle.wSubBrand);

                                System.out.println("物体颜色相似度:"+new String(stuVehicle.byColorSimilar,encode));

                                System.out.println("上半身物体颜色相似度:"+new String(stuVehicle.byUpperBodyColorSimilar,encode));

                                System.out.println("下半身物体颜色相似度:"+new String(stuVehicle.byLowerBodyColorSimilar,encode));

                                System.out.println("szSubText:"+new String(stuVehicle.szSubText,encode));



                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }


                            System.out.println("emVehicleTypeByFunc = " + trafficJunction.stTrafficCar.emVehicleTypeByFunc);
                            System.out.println("nSunBrand = " + trafficJunction.stTrafficCar.nSunBrand);
                            System.out.println("nBrandYear = " + trafficJunction.stTrafficCar.nBrandYear);
                            //save the picture
                            String   imageName="trafficJunction_"+System.currentTimeMillis()+".jpg";

                            String   savePath=picturePath+"/"+imageName;

                            ToolKits.savePicture(pBuf,dwBufSize,savePath);
                            System.out.println("save picture to "+savePath);

                            NetSDKLib.NET_TRAFFICCAR_BLACK_LIST stuBlackList
                                    = trafficCar.stuBlackList;
                            int nControlledRouteID
                                    = stuBlackList.nControlledRouteID;

                            System.out.println("nControlledRouteID = " + nControlledRouteID);
                            break;
                        }

                        default:
                            System.out.println(" emEventType:" + emEventType);
                            break;

                    }
                }
            }

            return 0;
        }

        // 获取附加物类型名称
        private String parseAttachmentType(int emType) {

            String emName;
            switch (emType) {
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_UNKNOWN:
                    emName = "未知类型";
                    break;
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_FURNITURE:
                    emName = "摆件";
                    break;
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_PENDANT:
                    emName = "挂件";
                    break;
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_TISSUEBOX:
                    emName = "纸巾盒";
                    break;
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_DANGER:
                    emName = "危险品";
                    break;
                case NetSDKLib.EM_COMM_ATTACHMENT_TYPE.COMM_ATTACHMENT_TYPE_PERFUMEBOX:
                    emName = "香水";
                    break;
                default:
                    emName = "类型数据有错误";
                    break;
            }
            return emName;
        }

    }
    /**
     * 智能分析退订
     *
     * @return 是否成功退订
     */
    public void detachAnalyseTaskResult() {
        System.out.println("detachAnalyseTaskResult:"+AttachHandle.longValue());

        boolean result = netsdk.CLIENT_DetachAnalyseTaskResult(AttachHandle);
        if (!result) {
            System.out.println("detach analyseTask result failed. error is " + ENUMERROR.getErrorMessage());
        }else {
            System.out.println("detachAnalyseTaskResult Succeed");
        }

    }

    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem(new CaseMenu.Item(this, "添加任务", "AddAnalyseTaskLEFTDETECTION"));
        menu.addItem(new CaseMenu.Item(this, "推送图片", "pushs"));
        menu.addItem(new CaseMenu.Item(this, "订阅分析", "attachAnalyseTaskResult"));
        menu.addItem(new CaseMenu.Item(this, "取消订阅分析", "detachAnalyseTaskResult"));
        menu.run();
    }
    // 配置登陆地址，端口，用户名，密码
    private String m_strIpAddr = "172.12.8.153";
    private int m_nPort = 37777;
    private String m_strUser = "admin";
    private String m_strPassword = "admin123";
    public static void main(String[] args) {
        VehicleDetectRuleInfoDemo demo=new VehicleDetectRuleInfoDemo();
        demo.InitTest();
        demo.RunTest();
        demo.EndTest();

    }

    /**
     * 初始化测试
     */
    public void InitTest() {
        VehicleDetectRuleInfoDemo.Init();

        this.loginWithHighLevel();
    }

    /**
     * 结束测试
     */
    public void EndTest() {
        System.out.println("End Test");
        this.logOut(); // 登出设备
        System.out.println("See You...");
        VehicleDetectRuleInfoDemo.cleanAndExit(); // 清理资源并退出
    }

}
